const mongoose = require('mongoose');
const Category = require('../models/Category');
const fs = require('fs');
const path = require('path');
require('dotenv').config();

const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/guan';

async function initData() {
    try {
        // 连接数据库
        await mongoose.connect(MONGODB_URI);
        console.log('MongoDB连接成功');

        // 读取JSON文件
        const jsonData = JSON.parse(fs.readFileSync(path.join(__dirname, '../../src/data/data.json'), 'utf8'));
        const { nsjz } = jsonData;

        // 清空现有数据
        await Category.deleteMany({});

        // 处理支出数据
        const expenseCategories = nsjz.expenses.type.map(category => ({
            ...category,
            type: 'expense',
            data: category.data.map(item => ({
                ...item,
                time: new Date(item.time)
            }))
        }));

        // 处理收入数据
        const incomeCategories = nsjz.income.type.map(category => ({
            ...category,
            type: 'income',
            data: category.data.map(item => ({
                ...item,
                time: new Date(item.time)
            }))
        }));

        // 插入数据
        await Category.insertMany([...expenseCategories, ...incomeCategories]);
        console.log('数据初始化成功');

        process.exit(0);
    } catch (error) {
        console.error('数据初始化失败:', error);
        process.exit(1);
    }
}

initData(); 